import React, {FC, useContext, useState} from 'react';
import "./index.less";
import {Button, Flex, Form, Input, message, Tooltip} from "antd";
import {history, Link, useModel} from "umi";
import {CloseSquareFilled, LockOutlined, UserOutlined} from "@ant-design/icons";
import {nanoid} from "nanoid";
import {flushSync} from 'react-dom';
import * as API from "@/services";
import {setAuthInfo} from '@/utils/auth';
import querystring from "query-string";
import {FormattedMessage, useIntl} from "react-intl";
import {DEFAULT_REGISTER_PATH as REGISTER_PATH} from "@kf-web-library/utils/es/constants";
import {HxConfigContext} from "@/layouts/HxConfigContext";


interface LoginPageProps {
}

const LoginPage: FC<LoginPageProps> = (props) => {
  const intl = useIntl();
  const [form] = Form.useForm();
  const {initialState, refresh, setInitialState} = useModel('@@initialState');
  const {authedRedirect} = useContext(HxConfigContext);
  const [loading, setLoading] = useState(false)


  const handleSubmit = async (values: API.PasswordLoginReq) => {
    const submitValues = {...values};
    // 登录
    try {
      setLoading(true);
      const resp = await API.passwordLogin({...submitValues}, {skipErrorHandler: true});
      if (resp.flag) {
        setAuthInfo(resp.data);
        message.success('登录成功！');
        const loggedInfo = await initialState?.fetchLoggedInfo?.();
        if (loggedInfo) {
          //同步等待 react 18 only, 避免异步时 app.tsx的layout中拿不到initialState的问题
          flushSync(() => {
            setInitialState((s) => ({
              ...s,
              ...loggedInfo,
            }));
          });
        }
        const currentUrl = new URL(window.location.href);
        const urlParams = currentUrl.searchParams;
        //尝试获取url中的redirect参数(地址), 如果有就重定向到这个地址,否则就去首页"/"
        const redirectTarget = urlParams.get('redirect') || '/';
        history.push({
          pathname: redirectTarget,
          hash: !!currentUrl?.hash ? currentUrl.hash.slice(1) : undefined,
        });
        return;
      }
    } catch (e: any) {
      if (e.response?.data?.msg) {
        message.error(e.response?.data?.msg)
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className={"login-page-container"}>
      <Form
        form={form}
        className={"tooltip-feedback-form"}
        feedbackIcons={({errors}) => ({
          error: (
            <Tooltip
              key="tooltipKey"
              title={errors?.map((error) => <div key={nanoid()}>{error}</div>)}
              color="red"
            >
              <CloseSquareFilled/>
            </Tooltip>
          ),
        })}
        autoComplete="off"
        onFinish={async (values) => {
          await handleSubmit(values as API.PasswordLoginReq);
        }}
      >
        <Form.Item
          name="loginName"
          rules={[
            {
              required: true,
              message: intl.formatMessage({id: `validation.loginName_require`})},
            {
              pattern: /^[\u4e00-\u9fa5a-zA-Z0-9_\-@.]{2,32}$/,
              message: intl.formatMessage({id: `validation.loginName_pattern`}),
            },
          ]}
          help=""
          hasFeedback={true}
        >
          <Input prefix={<UserOutlined />}
                 size={"large"}
                 placeholder={intl.formatMessage({id: `validation.loginName_require`})}/>
        </Form.Item>
        <Form.Item
          name="password"
          rules={[
            {required: true, message: intl.formatMessage({id: `validation.passwd_require`})},
            {min: 5, message: intl.formatMessage({id: `validation.passwd_min`})},
            {max: 50, message: intl.formatMessage({id: `validation.passwd_max`})},
          ]}
          help=""
          hasFeedback={true}
        >
          <Input.Password
            prefix={<LockOutlined/>}
            size={"large"}
            placeholder={intl.formatMessage({id: `validation.passwd_require`})}
          />
        </Form.Item>
        <Form.Item>
          <Button
            className={'login-submit-btn'}
            type="primary"
            htmlType="submit"
            size={"large"}
            loading={loading}
            block={true}
          >
            <FormattedMessage id="text.login"/>
          </Button>
        </Form.Item>
        <Form.Item>
          <Flex vertical={false} gap={6} justify={"space-between"}>
            <div>
              <FormattedMessage
                id="text.account-desc2"
                values={{
                  btn: (
                    <Link to={{
                      pathname: REGISTER_PATH,
                      search: authedRedirect ? querystring.stringify({redirect: authedRedirect}) : "",
                    }}>
                      <FormattedMessage id="text.register"/>
                    </Link>
                  )
                }}
              />
            </div>
            <div>
              <Link to={{
                pathname: "/forgot",
                search: authedRedirect ? querystring.stringify({redirect: authedRedirect}) : "",
              }}>
                <FormattedMessage id="text.forgot"/>
              </Link>
            </div>
          </Flex>
        </Form.Item>
      </Form>
    </div>
  );
};

export default LoginPage;
